package br.unicamp.ic.lis.docseaservice.model.queryresult;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.log4j.Logger;

import br.unicamp.ic.lis.docseaservice.model.vo.LocationUri;

import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

public class LocationUriListHandler implements
		ResultSetHandler<List<LocationUri>> {

	private static Logger LOG = Logger.getLogger(LocationUriListHandler.class);

	@Override
	public List<LocationUri> handle(ResultSet rs) throws SQLException {
		List<LocationUri> list = new ArrayList<LocationUri>();

		while (rs.next()) {
			LocationUri lu = new LocationUri();
			lu.setId(rs.getLong("id"));
			try {
				String result = rs.getObject("location").toString();
				String[] location = result.split(";");
				Point point = (Point) new WKTReader().read(location[1]);
				int srid = Integer.parseInt(location[0].substring(5));
				point.setSRID(srid);
				lu.setLocation(point);
			} catch (ParseException e) {
				LOG.error("Failed to parse geometry type", e);
			}
			lu.setUri(rs.getString("uri"));
			lu.setCountry(rs.getString("country"));
			lu.setState(rs.getString("state"));
			lu.setCity(rs.getString("city"));
			list.add(lu);
		}
		return list;
	}
}
